<template>
  <el-dialog v-loading="loading" title="分配角色" :visible="showRoleDialog" @close="handleClose" @open="handleOpen">
    <el-checkbox-group v-model="checkList">
      <el-checkbox v-for="item in roleList" :key="item.id" :label="item.id">{{ item.name }}</el-checkbox>
    </el-checkbox-group>

    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="clickSubmit">确定</el-button>
    </template>
  </el-dialog>
</template>

<script>
import { reqGetRoleList } from '@/api/setting'
import { reqGetUserDetailById } from '@/api/user'
import { reqAssignRoles } from '@/api/employees'
export default {
  props: {
    showRoleDialog: {
      type: Boolean,
      default: false // default 默认值
    },
    userId: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      checkList: [], // 多选框收集数据
      roleList: [], // 所有角色信息
      loading: false
    }
  },
  methods: {
    // X按钮
    handleClose() {
      this.$emit('update:showRoleDialog', false)
      this.checkList = [] // 关闭时清空重置checkList
    },
    // 点击角色弹窗时调用open函数获取axios数据
    handleOpen() {
      this.loading = true
      Promise.all([this.getRoleList(), this.getUserDetail()]).then(() => {
        this.loading = false
      })
    },
    // 获取所有角色数据
    async getRoleList() {
      const { data: { rows }} = await reqGetRoleList(1, 1000)
      this.roleList = rows
    },
    // 获取员工已有角色
    async  getUserDetail() {
      const { data: { roleIds }} = await reqGetUserDetailById(this.userId)
      this.checkList = roleIds || []
    },
    // 给员工分配角色
    async clickSubmit() {
      const res = await reqAssignRoles({ id: this.userId, roleIds: this.checkList })
      this.$message.success(res.message)
      this.handleClose()
    }
  }
}
</script>

<style lang="scss" scoped>
.assign-role {
  ::v-deep {
    .el-checkbox {
      font-size: 30px;
    }
  }
}
</style>
